package com.silvervine.macnets;

import android.Manifest;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.silvervine.base.ui.SilvervineActivity;
import com.silvervine.base.utils.AppUtils;
import com.silvervine.macnets.consts.LoginStatus;
import com.silvervine.macnets.utils.PgTunnel;
import com.silvervine.macnets.utils.UserUtils;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import kr.co.namee.permissiongen.PermissionFail;
import kr.co.namee.permissiongen.PermissionGen;
import kr.co.namee.permissiongen.PermissionSuccess;

import static com.silvervine.macnets.consts.EventTag.FORCE_USER_OFFLINE;
import static com.silvervine.macnets.consts.EventTag.PUSH_USER_LOGIN_DATA;

public class LoginActivity extends SilvervineActivity {

    private boolean       isGetPermission = false;
    private UserLoginTask mAuthTask       = null;
    private EditText mEmailView;
    private EditText etPwd;
    private TextView tvDescription;
    private View     mProgressView;
    private View     mLoginFormView;
    StringBuilder stringBuilder = new StringBuilder("正在准备收集作战信息...");
    private String[] loginParams = new String[2];
    private String   email       = "";
    private String   password    = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        EventBus.getDefault().register(this);
        mEmailView = (EditText) findViewById(R.id.email);
        etPwd = (EditText) findViewById(R.id.etPwd);
        tvDescription = (TextView) findViewById(R.id.tvDescription);
        mEmailView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == EditorInfo.IME_ACTION_DONE || id == EditorInfo.IME_NULL) {
                    attemptLogin();
                    return true;
                }
                return false;
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                AppUtils.closeBoard(LoginActivity.this, mEmailView);
                if (isGetPermission) {
                    attemptLogin();
                } else {
                    requestPermission();
                }
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        mEmailView.setText(UserUtils.getUser(this));
    }

    private void attemptLogin() {
        if (mAuthTask != null) {
            return;
        }
        // Reset errors.
        mEmailView.setError(null);
        // Store values at the time of the login attempt.
        email = mEmailView.getText().toString();
        boolean cancel    = false;
        View    focusView = null;

        // Check for a valid email address.
        if (TextUtils.isEmpty(email)) {
            mEmailView.setError(getString(R.string.error_field_required));
            focusView = mEmailView;
            cancel = true;
        } else if (!isEmailValid(email)) {
            mEmailView.setError(getString(R.string.error_invalid_email));
            focusView = mEmailView;
            cancel = true;
        } else {
            email = email.trim();
            loginParams = email.split("@");
            if (TextUtils.isEmpty(loginParams[0]) || TextUtils.isEmpty(loginParams[1])) {
                mEmailView.setError(getString(R.string.error_invalid_email));
                focusView = mEmailView;
                cancel = true;
            }
        }


        etPwd.setError(null);
        // Store values at the time of the login attempt.
        password = etPwd.getText().toString();
        if (TextUtils.isEmpty(password)) {
            etPwd.setError(getString(R.string.error_field_required));
            focusView = etPwd;
            cancel = true;
        }


        if (cancel) {
            focusView.requestFocus();
        } else {
            mAuthTask = new UserLoginTask(loginParams[0], loginParams[1], password);
            mAuthTask.execute((Void) null);
        }
    }

    private boolean isEmailValid(String email) {
        return email.contains("@");
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
        // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
        // for very easy animations. If available, use these APIs to fade-in
        // the progress spinner.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            // The ViewPropertyAnimator APIs are not available, so simply show
            // and hide the relevant UI components.
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * Represents an asynchronous login/registration task used to authenticate
     * the user.
     */
    public class UserLoginTask extends AsyncTask<Void, Void, Integer> {

        String loginId, domain, password;

        UserLoginTask(String id, String domain, String password) {
            this.loginId = id;
            this.domain = domain;
            this.password = password;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            PgTunnel.getInstance().stop();
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("找到目标位置...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("作战准备...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("全体都有...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("全体都有...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("炮兵准备...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("装弹...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("装弹完毕...");
            tvDescription.setText(stringBuilder);
            stringBuilder.append("\n").append("发射...");
            tvDescription.setText(stringBuilder);
        }

        @Override
        protected Integer doInBackground(Void... params) {
            PgTunnel.getInstance().startTunnel(loginId, domain, password);
            return PgTunnel.getInstance().getLoginStatusCode();
        }

        @Override
        protected void onPostExecute(final Integer code) {
            mAuthTask = null;
            if (code == 0) {
//                PgTunnel.getInstance().getMsgAndOffline();
                loginSuccess();
            } else {
                loginError(LoginStatus.getMessage(code));
            }
        }

        @Override
        protected void onCancelled() {
            mAuthTask = null;
        }
    }

    private void loginSuccess() {
        stringBuilder.append("\n").append("击中目标...");
        tvDescription.setText(stringBuilder);
        stringBuilder.append("\n").append("连接成功...");
        tvDescription.setText(stringBuilder);
        UserUtils.updateUser(this, email);
    }

    private void loginError(String message) {
        stringBuilder.append("\n").append("射偏了...");
        tvDescription.setText(stringBuilder);
        stringBuilder.append("\n").append(message);
        tvDescription.setText(stringBuilder);
        mEmailView.setError(message);
        mEmailView.requestFocus();
    }

    private void sendNotification(String errMessage) {
        NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(email)
                .setContentText(email + "," + errMessage);
        notifyManager.notify(1, builder.build());
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        PermissionGen.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
    }

    @PermissionSuccess(requestCode = 100)
    public void permissionSuccess() {
        isGetPermission = true;
    }

    @PermissionFail(requestCode = 100)
    public void permissionFailed() {
        isGetPermission = false;
        Toast.makeText(this, "为确保功能正常,请允许权限申请!", Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        requestPermission();
        super.onResume();
    }

    public void requestPermission() {
        PermissionGen.with(this)
                .addRequestCode(100)
                .permissions(
                        Manifest.permission.INTERNET,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.ACCESS_WIFI_STATE,
                        Manifest.permission.READ_PHONE_STATE
                )
                .request();
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            Log.d("pgLiveCapture", "onKeyDown, KEYCODE_BACK");
            ExitDialog();
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    private DialogInterface.OnClickListener m_DlgClick = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            if (which == AlertDialog.BUTTON_POSITIVE) {
                PgTunnel.getInstance().stop();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        }
    };

    @Subscriber(tag = PUSH_USER_LOGIN_DATA)
    public void forceQuite(String message) {
        tvDescription.setText(stringBuilder);
        stringBuilder.append("\n").append(message);
        tvDescription.setText(stringBuilder);
    }

    @Subscriber(tag = FORCE_USER_OFFLINE)
    public void offline(String message) {
        PgTunnel.getInstance().stop();
        loginError(message);
        sendNotification(message);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void ExitDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("注意");
        builder.setMessage("退出后连接将中断,是否退出?");
        builder.setPositiveButton("是", m_DlgClick);
        builder.setNegativeButton("否", m_DlgClick);
        builder.show();
    }
}

